package com.junlong0716.enjoylearning.ui

import android.annotation.TargetApi
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.R
import com.junlong0716.module.common.rxbus.RxBus
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import kotlinx.android.synthetic.main.activity_play_download_video.*
import java.io.File

class PlayDownloadVideoActivity : AppCompatActivity() {
    var orientationUtils: OrientationUtils? = null
    private var videoPath: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play_download_video)
        RxBus.getDefault().register(this)
        val downloadFile = intent.getSerializableExtra("DOWNLOAD_VIDEO_FILE") as File
        if (downloadFile.exists()) {
            videoPath = Uri.parse("file://" + downloadFile.absolutePath).toString();
        } else {
            ToastUtils.showShort("文件不存在！")
            finish()
        }
        initVideoView(videoPath)
    }


    private fun initVideoView(source1: String) {
        video_player.setUp(source1, true, "")
        //增加title
        video_player.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        video_player.getBackButton().setVisibility(View.VISIBLE);

        //设置旋转
        orientationUtils = OrientationUtils(this, video_player)

        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        video_player.getFullscreenButton().setOnClickListener(View.OnClickListener { orientationUtils!!.resolveByClick() })
        //设置返回按键功能
        video_player.getBackButton().setOnClickListener(View.OnClickListener { onBackPressed() })
        video_player.startPlayLogic();
    }




    override fun onPause() {
        super.onPause()
        video_player.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        video_player.onVideoResume()
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils!!.releaseListener();
        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }
    }


    override fun onBackPressed() {
        //先返回正常状态
        if (orientationUtils!!.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            video_player.getFullscreenButton().performClick();
            return;
        }
        //释放所有
        video_player.setVideoAllCallBack(null);
        super.onBackPressed()
    }

}
